import { EventTypeStr, SocketMag, SocketType } from "./SocketMag";
import SetPanel from "./SetPanel";
import { EventCtrl } from "./EventCtrl";
import { GameData } from "./GameData";
import { TipMag } from "./TipsUI";
import { Glodef } from "../Glodef";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SomeoneMenu extends cc.Component {

    public lab_tip1: cc.Label = null;
    public lab_tip2: cc.Label = null;
    public lab_time: cc.Label = null;
    public lab_room: cc.Label = null;
    public Rtxt_player: cc.RichText = null;
    public lab_RunText: cc.RichText = null;
    public btn_host: cc.Node = null;
    public btn_return: cc.Node = null;
    public draw: cc.Graphics = null;
    public Gr_Write: cc.Node = null;
    public btn_join: cc.Node = null;
    public lab_HostPlayer: cc.Label = null;
    public EditBox_resule: cc.EditBox = null;
    public btn_send: cc.Node = null;
    public btn_copy: cc.Node = null;
    public static Inst: SomeoneMenu = null;
    public m_PopView: cc.Node = null;

    onLoad() {
        SomeoneMenu.Inst = this;
        //不想再编辑器上拖来拖去
        this.lab_tip1 = this.node.getChildByName('lab_tip1').getComponent(cc.Label);
        this.lab_tip2 = this.node.getChildByName('lab_tip2').getComponent(cc.Label);
        this.lab_time = this.node.getChildByName('lab_time').getComponent(cc.Label);
        this.lab_room = this.node.getChildByName('lab_room').getComponent(cc.Label);
        this.lab_HostPlayer = this.node.getChildByName('lab_HostPlayer').getComponent(cc.Label);
        this.Rtxt_player = this.node.getChildByName('Rtxt_player').getComponent(cc.RichText);
        this.lab_RunText = this.node.getChildByName('RunText').getComponent(cc.RichText);
        this.btn_host = this.node.getChildByName('btn_host');
        this.btn_return = this.node.getChildByName('btn_return');
        this.btn_join = this.node.getChildByName('btn_join');
        this.Gr_Write = this.node.getChildByName('Gr_Write');
        this.draw = this.Gr_Write.getChildByName("GraphicsNode").getComponent(cc.Graphics);
        this.btn_copy = this.node.getChildByName('btn_copy');
        this.EditBox_resule = this.node.getChildByName('EditBox_resule').getComponent(cc.EditBox);
        this.btn_send = this.node.getChildByName('btn_send');
        cc.macro.ENABLE_MULTI_TOUCH = false;
    }

    start() {
        SocketMag.getInstance();
        EventCtrl.GetInst();
        this.Refresh();
        this.setTip1(false);
        this.setHostLab();
        new TipMag();

        this.Gr_Write.on(cc.Node.EventType.TOUCH_START, this.OnTouchStart, this)
        this.Gr_Write.on(cc.Node.EventType.TOUCH_MOVE, this.OnTouchMove, this)
        this.Gr_Write.on(cc.Node.EventType.TOUCH_END, this.OnTouchEnd, this)
        this.Gr_Write.on(cc.Node.EventType.TOUCH_CANCEL, this.OnTouchEnd, this)
        this.OpenPopView(SocketType.setName);

        this.btn_join.on(cc.Node.EventType.TOUCH_END, () => {
            this.OpenPopView(SocketType.joinRoom);
        }, this);

        this.btn_host.on(cc.Node.EventType.TOUCH_END, () => {
            SocketMag.getInstance().SendMsg({ roomid: GameData.Inst().m_nRoomid, userid: GameData.Inst().m_nUserid }, SocketType.reqHost);
        }, this);

        this.btn_return.on(cc.Node.EventType.TOUCH_END, () => {
            SocketMag.getInstance().SendMsg({ userid: GameData.Inst().m_nUserid }, SocketType.returnSelfRoom);
        }, this);

        this.btn_send.on(cc.Node.EventType.TOUCH_END, () => {
            let str = this.EditBox_resule.string
            if (!str) return;
            this.EditBox_resule.string = '';
            SocketMag.getInstance().SendMsg({
                roomid: GameData.Inst().m_nRoomid,
                userid: GameData.Inst().m_nUserid,
                text: str
            }, SocketType.sendResule);

        }, this);

        this.btn_copy.on(cc.Node.EventType.TOUCH_END, () => {
            Glodef.webCopyString(this.roomid + '');
        }, this);

    }

    public OpenPopView(type: SocketType) {
        cc.resources.load('SetPanel', cc.Prefab, (error: Error, prefab: cc.Prefab) => {
            let instan = cc.instantiate(prefab);
            this.m_PopView = instan;
            this.node.addChild(instan);
            (instan.getComponent('SetPanel') as SetPanel).SwitchPage(type);
        });
    }

    public setTip1(boo: boolean = false) {
        this.lab_tip1.string = boo ? '服务器已连接' : '服务器未连接';
        this.lab_tip1.node.color = boo ? cc.Color.GREEN : cc.Color.RED;
    }
    public setTip2(boo: boolean = false) {
        this.lab_tip2.string = boo ? '游戏进行中' : '游戏未开始';
        this.lab_tip2.node.color = boo ? cc.Color.GREEN : cc.Color.RED;
    }

    public setHostLab() {
        let Hostuserid = GameData.Inst().m_nHostUserid
        if (!Hostuserid) {
            this.lab_HostPlayer.string = '';
            return
        };
        this.lab_HostPlayer.string = '主持人：' + GameData.Inst().GetHostName();
    }

    //跑马灯
    public m_vSuccName: string[] = [];
    public m_brunText: boolean = false;
    public runText(sName: string) {

        this.m_brunText = true;
        this.lab_RunText.string = '<color=#ffffff>玩家：</c>' + '<color=#0fffff> ' + sName + ' </color>'
            + '<color=#0ff00f>回答正确</color>';
        this.lab_RunText.node.x = cc.winSize.width / 2;
        let moveLen = cc.winSize.width + this.lab_RunText.node.width;
        cc.tween(this.lab_RunText.node).by(5, { x: -moveLen }).call(() => {

            this.m_brunText = false;
            let shiftStr = this.m_vSuccName.shift();
            if (shiftStr) this.runText(shiftStr);
        }).start();
    }

    public Refresh() {
        let boo1 = GameData.Inst().m_bstartGame;//开始
        let boo2 = boo1 && !GameData.Inst().checkIsHost();//开始且不是庄家
        let boo3 = !boo1 && !GameData.Inst().m_nHostUserid && GameData.Inst().GetGamePlayerCount() > 1;
        this.setTip2(boo1);
        this.btn_host.active = boo3;
        this.lab_time.node.active = boo1;
        this.EditBox_resule.node.active = boo2;
        this.btn_send.active = boo2;

        //加入其他房间： 自己的房间，并且只有一个
        //返回自己的房间： 别的房间，没有开始游戏
        if (GameData.Inst().m_vPlayerName)
            this.btn_join.active = Object.keys(GameData.Inst().m_vPlayerName).length == 1 && GameData.Inst().cheakRoomHolder();
        this.btn_return.active = !GameData.Inst().m_bstartGame && !GameData.Inst().cheakRoomHolder();
    }

    private DJsFun: Function;
    public DJsTime(Time: number) {
        this.lab_time.node.active = true;
        this.lab_time.string = Time.toString();
        this.DJsFun = () => {
            Time--;
            this.lab_time.string = Time.toString();
            if (Time == 0) {
                this.StopDJs();
            }
        }
        this.schedule(this.DJsFun, 1);
    }

    public StopDJs() {
        if (this.DJsFun) {
            this.unschedule(this.DJsFun);
            this.DJsFun = null;
        }
    }

    public roomid = 0;
    public setRoomInfo(roomid: number, _playerName: any) {
        this.roomid = roomid;
        this.lab_room.string = '房间号：' + roomid;
        let playerName = JSON.parse(JSON.stringify(_playerName));
        let txt = '<color=#ffffff>房间玩家：</c>';
        let nMasterid = GameData.Inst().m_nCurRoomMasterid;
        let sMasterName = playerName[nMasterid];
        let nHostId = GameData.Inst().m_nHostUserid;

        if (sMasterName) {
            txt += '<color=#0fff00>' + sMasterName + '</color>';
            delete playerName[nMasterid];
        }
        if (nHostId > 0) {
            txt += '<color=#0f0000>' + (sMasterName ? '、' : '') + playerName[nHostId] + '</color>';
            delete playerName[nHostId]
        }
        for (const key in playerName) {
            txt += '<color=#0fffff>' + (sMasterName || nHostId ? '、' : '') + playerName[key] + '</color>';
        }
        this.Rtxt_player.string = txt;
    }

    public isMove: boolean = false;
    private m_nLastPos: cc.Vec2 = null;
    private m_initPos: cc.Vec2 = null;
    private m_vMovePoint: cc.Vec2[] = [];
    public m_isMaster: boolean = false//是否是房主
    private m_obj = {};
    private m_nLine = 1;

    private OnTouchStart(even) {

        //只有房主开始游戏的时候才能绘画
        if (!GameData.Inst().checkIsHost() || !GameData.Inst().m_bstartGame) return;

        let initPos = even.getLocation();
        this.m_initPos = this.Gr_Write.convertToNodeSpaceAR(initPos);
        (this["draw"] as cc.Graphics).moveTo(this.m_initPos.x, this.m_initPos.y);
        this.m_obj[this.m_nLine++] = [];
        this.m_nLastPos = null;
        let obj = { x: this.m_initPos.x, y: this.m_initPos.y, type: 1, roomid: GameData.Inst().m_nRoomid }
        SocketMag.getInstance().SendMsg(obj, SocketType.game);
    }


    private OnTouchMove(even) {

        if (!GameData.Inst().checkIsHost() || !GameData.Inst().m_bstartGame) return;

        let initPos = even.getLocation();
        let pos = this.Gr_Write.convertToNodeSpaceAR(initPos);
        if (this.m_initPos == pos) return;
        this["draw"].lineTo(pos.x, pos.y);
        this["draw"].stroke();

        if (this.m_nLastPos == null) {
            this.m_nLastPos = this.node.convertToNodeSpaceAR(initPos);
            this.m_vMovePoint.push(this.m_nLastPos);
        }
        else {
            let newPos = this.node.convertToNodeSpaceAR(initPos);
            let distance = this.m_nLastPos.sub(newPos).mag();
            if (distance >= 1) {
                this.m_vMovePoint.push(newPos);
                this.m_nLastPos = newPos;
            }
        }

        let obj = { x: pos.x, y: pos.y, type: 2, roomid: GameData.Inst().m_nRoomid }
        SocketMag.getInstance().SendMsg(obj, SocketType.game);
    }


    private OnTouchEnd() {
        if (!GameData.Inst().checkIsHost() || !GameData.Inst().m_bstartGame) return;

        if (this.m_vMovePoint.length <= 2 || this.isMove) return;
    }


    public NetDraw(data) {

        if (GameData.Inst().checkIsHost()) return;

        if (data.type == 1) {
            this["draw"].moveTo(data.x, data.y);
        }
        else if (data.type == 2) {
            this["draw"].lineTo(data.x, data.y);
            this["draw"].stroke();
        }
    }

    public ReadyGame() {
        this["draw"].clear();
        this.setTip2(false);
        GameData.Inst().m_bstartGame = false;
        this.lab_time.node.active = false;
        this.EditBox_resule.node.active = false;
        this.setHostLab();
        this.Refresh();
    }
}
